import cron from 'node-cron'
import dayjs from 'dayjs'
import { initializeDatabaseConnections } from '@/utils/database'
import { consoleLogger, errorLogger, initializeLogConfig } from '@/utils/logger'
import cronTasks from '@/utils/cron'

// 初始化函数
export const appInit = async () => {
  // 注入日志配置
  initializeLogConfig()
  // 开启数据连接
  await initializeDatabaseConnections()

  // 定时任务：每分钟执行一次
  cron.schedule('* * * * *', async () => {
    try {
      consoleLogger.info(`【${dayjs().format('YYYY-MM-DD HH:mm:ss')}】开始执行定时任务啦！`)
      await Promise.all(cronTasks.map(task => task()))
    } catch (e) {
      errorLogger.error('定时任务异常', e)
    }
  })
  consoleLogger.warn(`Server is running at http://localhost:${process.env.PORT}`)
}
